package com.qiantu.phone.ui.adapter;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.hjq.widget.swipelayout.SimpleSwipeListener;
import com.hjq.widget.swipelayout.SwipeLayout;
import com.hjq.widget.swipelayout.adapters.RecyclerSwipeAdapter;
import com.lxj.xpopup.XPopup;
import com.qiantu.api.db.LLDeviceActionDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.LinkageBean;
import com.qiantu.api.entity.SceneDetailBean;
import com.qiantu.api.entity.UniversalDeviceData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.glide.GlideApp;
import com.qiantu.phone.ui.activity.AddTaskActivity;
import com.qiantu.phone.ui.activity.AddTaskActivityNew;
import com.qiantu.phone.ui.dialog.SceneTaskSortDialog;
import com.qiantu.phone.ui.uiutil.DeviceType;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;
import com.qiantu.phone.ui.uiutil.LLSceneLinkageUtil;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class LinkageTaskAdapter extends RecyclerSwipeAdapter {

    public String targetSerialNo;

    public boolean isNewVersion;

    private List<LinkageBean.LinkageTask> mData;

    public List<LinkageBean.LinkageTask> getData() {
        return mData;
    }

    public void setData(List<LinkageBean.LinkageTask> data) {
        this.mData = data;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.linkage_task_item, parent, false);
        return new TaskItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        TaskItemViewHolder vh = (TaskItemViewHolder) viewHolder;
        LinkageBean.LinkageTask linkageTask = mData.get(position);
        switch (linkageTask.getTaskType()) {
            case 1:
            case 9:
                vh.value.setVisibility(View.GONE);
                String deviceSerialNo;
                DeviceBean device;
                if(linkageTask.getTaskType() == 9){
                    deviceSerialNo = linkageTask.getDeviceGroupSerialNo();
                    device = LLDeviceDBManager.getInstance(AppApplication.getInstance()).get(deviceSerialNo);
                }else{
                    deviceSerialNo = linkageTask.getDeviceSerialNo();
                    device = LLDeviceDBManager.getInstance(AppApplication.getInstance()).get(deviceSerialNo);
                }
                if(device != null){
                    vh.valuesLy.setVisibility(View.VISIBLE);
                    GlideApp.with(vh.icon)
                            .load(device.getOnImageUrl())
                            .placeholder(vh.icon.getDrawable())
                            .into(vh.icon);
                    String type = null;
                    String deviceType = null;
                    if (device != null) {
                        type = device.getType();
                        deviceType = device.getDeviceType();
                    }
                    Map<String, String> status;
                    if(linkageTask.getTaskType() == 9){
                        status = linkageTask.getStateData().getStatus();
                    }else{
                        status = linkageTask.getDeviceStateData().getStatus();
                    }

                    List<String> values = new ArrayList<>();
                    if (device.getDeviceType().equals(DeviceType.UNIVERSAL_SEQUENCER.stringType) || device.getDeviceType().equals(DeviceType.UNIVERSAL_PROJECTOR.stringType) || device.getDeviceType().equals(DeviceType.UNIVERSAL_PLAYER.stringType) || device.getDeviceType().equals(DeviceType.UNIVERSAL_PA.stringType) || device.getDeviceType().equals("universal_freshair")){
                        List<UniversalDeviceData> datas = LLDeviceActionDBManager.getInstance(AppApplication.getInstance()).getDeviceDatasByDeviceSerialNo(device.getDeviceSerialNo());
                        Set<String> keys = status.keySet();
                        for(String key : keys){
                            for(UniversalDeviceData data : datas){
                                if(key.equals(data.getActionIdentifier()) && status.get(key).equals(data.getRangeIdentifier())){
                                    if(device.getDeviceType().equals("universal_sequencer")){
                                        values.add(String.format("%s:%s",data.getCombineName(),data.getRangeName()));
                                    }else{
                                        values.add(data.getRangeName());
                                    }
                                    break;
                                }
                            }
                        }
                    }else{
                        values = LLDeviceUtil.getValueStr_max3(type, deviceType, status, deviceSerialNo);
                    }
                    vh.swipeLayout.setSelected(targetSerialNo != null && targetSerialNo.equals(deviceSerialNo));
                    if (values.size() == 0) {
                        vh.value1.setVisibility(View.GONE);
                        vh.value2.setVisibility(View.GONE);
                        vh.value3.setVisibility(View.GONE);
                    } else if (values.size() == 1) {
                        vh.value1.setVisibility(View.VISIBLE);
                        vh.value1.setText(values.get(0));
                        vh.value2.setVisibility(View.GONE);
                        vh.value3.setVisibility(View.GONE);
                    } else if (values.size() == 2) {
                        vh.value1.setVisibility(View.VISIBLE);
                        vh.value1.setText(values.get(0));
                        vh.value2.setVisibility(View.VISIBLE);
                        vh.value2.setText(values.get(1));
                        vh.value3.setVisibility(View.GONE);
                    } else {
                        vh.value1.setVisibility(View.VISIBLE);
                        vh.value1.setText(values.get(0));
                        vh.value2.setVisibility(View.VISIBLE);
                        vh.value2.setText(values.get(1));
                        vh.value3.setVisibility(View.VISIBLE);
                        vh.value3.setText(values.get(2));
                    }
                    vh.value2.setVisibility(View.GONE);
                    vh.value3.setVisibility(View.GONE);
                    vh.name.setText(device.getName());
                }else{
                    vh.valuesLy.setVisibility(View.GONE);
                    vh.name.setText("未找到设备");
                    GlideApp.with(AppApplication.getInstance())
                            .load(linkageTask.getImageUrl())
                            .into(vh.icon);
                }
                break;
            case 2:
                setNotDeviceIconAndValue(vh, linkageTask);
                vh.name.setText(R.string.delay_interval);
                break;
            case 3:
                setNotDeviceIconAndValue(vh, linkageTask);
                vh.name.setText(R.string.push_message);
                break;
            case 4:
                setNotDeviceIconAndValue(vh, linkageTask);
                vh.name.setText(R.string.linkage_start_stop);
                break;

            case 5:
                setNotDeviceIconAndValue(vh, linkageTask);
                vh.name.setText(R.string.one_key_scene);
                break;
        }
        vh.swipeLayout.addSwipeListener(new SimpleSwipeListener() {
            @Override
            public void onOpen(SwipeLayout layout) {
                viewHolder.setIsRecyclable(false);
            }

            @Override
            public void onClose(SwipeLayout layout) {
                viewHolder.setIsRecyclable(true);
            }
        });
        vh.ly.setTag(position);
        vh.ly.setOnClickListener(listener);
        vh.delayTime.setOnClickListener(listener);
        vh.delayTime.setTag(position);
        vh.deleteImage.setTag(position);
        vh.deleteImage.setOnClickListener(listener);
        vh.addImage.setTag(position);
        vh.addImage.setOnClickListener(listener);
        vh.copyImage.setTag(position);
        vh.copyImage.setOnClickListener(listener);
        vh.sortTextView.setTag(position);
        vh.sortTextView.setOnClickListener(listener);
        mItemManger.bind(viewHolder.itemView, position);//实现只展现一条列表项的侧滑区域
        vh.sortTextView.setText(String.valueOf(position + 1));
        if(linkageTask.getTaskType() == 5 || linkageTask.getTaskType() == 4 || linkageTask.getTaskType() == 3){
            vh.delayTime.setVisibility(View.GONE);
        }else if(linkageTask.getTriggerTime() == 0){
            vh.delayTime.setVisibility(View.VISIBLE);
            vh.delayTime.setText("立即执行");
        }else{
            vh.delayTime.setVisibility(View.VISIBLE);
            String time = String.format("%02d:%02d后执行",linkageTask.getTriggerTime()/1000/60,linkageTask.getTriggerTime()/1000%60);
            vh.delayTime.setText(time);
        }
    }

    private void setNotDeviceIconAndValue(TaskItemViewHolder vh, LinkageBean.LinkageTask linkageTask){
        vh.icon.setImageDrawable(LLSceneLinkageUtil.getTaskIcon(linkageTask.getTaskType()));
        vh.value.setVisibility(View.VISIBLE);
        vh.valuesLy.setVisibility(View.GONE);
        vh.value.setText(LLSceneLinkageUtil.makeTaskBriefing(linkageTask));
    }

    @Override
    public int getItemCount() {
        return mData == null ? 0 : mData.size();
    }

    @Override
    public long getItemId(int position) {
        return super.getItemId(position);
    }

    @Override
    public int getSwipeLayoutResourceId(int position) {
        return R.id.swipe_layout;
    }

    private final View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = (int) v.getTag();
            if (v.getId() == R.id.add_image) {

                Intent intent = null;
                if(isNewVersion){
                    intent = new Intent(v.getContext(), AddTaskActivityNew.class);
                }else{
                    intent = new Intent(v.getContext(), AddTaskActivity.class);
                }
                intent.putExtra("position", position);
                intent.putExtra("type", AddTaskActivity.TYPE_LINKAGE);
                v.getContext().startActivity(intent);
                mItemManger.closeItem(position);
            } else if (v.getId() == R.id.delete_image) {
                if(mClickListener != null){
                    mClickListener.onDelete(position);
                }
            } else if (v.getId() == R.id.ly) {
                if (mItemManger.isOpen(position)) {
                    mItemManger.closeItem(position);
                } else {
                    if(mClickListener != null){
                        mClickListener.onEdit(position);
                    }
                }
            }else if(v.getId() == R.id.sort_image){
                mClickListener.onSort(position);
            }else if(v.getId() == R.id.copy_image){
                LinkageBean.LinkageTask taskBean = mData.get(position);
                Gson gson = new Gson();
                String json = gson.toJson(taskBean);
                LinkageBean.LinkageTask newBean = gson.fromJson(json,LinkageBean.LinkageTask.class);
                newBean.setTaskSerialNo("");
                mData.add(position,newBean);
                notifyDatasetChanged();
                mItemManger.closeItem(position);
            }else if(v.getId() == R.id.delay_time){
                if(mClickListener != null){
                    mClickListener.onDelay(position);
                }
            }
        }
    };





    private class TaskItemViewHolder extends RecyclerView.ViewHolder {
        public SwipeLayout swipeLayout;
        public LinearLayout seeLayout;
        public TextView sortTextView;
        public ImageView copyImage;
        public ImageView addImage;
        public ImageView deleteImage;
        public ImageView icon;
        public TextView name;
        public TextView delayTime;
        public TextView value;
        public TextView value1;
        public TextView value2;
        public TextView value3;
        public LinearLayout valuesLy;
        public View ly;

        public TaskItemViewHolder(@NonNull @NotNull View itemView) {
            super(itemView);
            swipeLayout = itemView.findViewById(R.id.swipe_layout);
            seeLayout = itemView.findViewById(R.id.see_layout);
            sortTextView = itemView.findViewById(R.id.sort_image);
            copyImage = itemView.findViewById(R.id.copy_image);
            addImage = itemView.findViewById(R.id.add_image);
            deleteImage = itemView.findViewById(R.id.delete_image);
            icon = itemView.findViewById(R.id.icon);
            name = itemView.findViewById(R.id.name);
            delayTime = itemView.findViewById(R.id.delay_time);
            value = itemView.findViewById(R.id.value);
            value1 = itemView.findViewById(R.id.value1);
            value2 = itemView.findViewById(R.id.value2);
            value3 = itemView.findViewById(R.id.value3);
            valuesLy = itemView.findViewById(R.id.status_ly);
            ly = itemView.findViewById(R.id.ly);
        }
    }


    private ClickListener mClickListener;
    public void setClickListener(@Nullable ClickListener listener) {
        mClickListener = listener;
    }

    public interface ClickListener {
        void onDelete(int position);
        void onEdit(int position);
        void onSort(int position);
        void onDelay(int position);
    }
}
